package com.maychat.controller;

import com.maychat.config.Consts;
import com.maychat.controller.base.BaseController;
import com.maychat.exception.BusinessException;
import com.maychat.exception.NoAuthException;
import com.maychat.pojo.Result;
import com.maychat.pojo.UserInfo;
import com.maychat.pojo.UserInfoToken;
import com.maychat.service.UserInfoService;
import com.maychat.websocket.ChannelContextUtils;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/userInfo")
public class UserInfoController extends BaseController {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    private ChannelContextUtils channelContextUtils;

    @GetMapping("/getMyUserInfo")
    public Result getMyUserInfo() throws NoAuthException {
        UserInfoToken tokenObj = getTokenObj();
        UserInfo userInfo = userInfoService.selectUserInfoById(tokenObj.getUserId());
        return Result.success(userInfo);
    }

    @PutMapping("/saveMyUserInfo")
    public Result saveMyUserInfo(UserInfo userInfo, MultipartFile avatarFull, MultipartFile avatarSmall) throws NoAuthException, IOException {
        UserInfoToken tokenObj = getTokenObj();
        userInfo.setUserId(tokenObj.getUserId());
        userInfo.setLastLoginTime(null);
        userInfo.setCreateTime(null);
        userInfo.setPassword(null);
        userInfo.setStatus(null);
        userInfoService.updateUserInfoById(userInfo, avatarSmall, avatarFull);
        return this.getMyUserInfo();
    }

    @PutMapping("/updatePassword")
    public Result updatePassword(
            @NotBlank @Pattern(regexp = Consts.REGEX_PASSWORD) String oldPassword,
            @NotBlank @Pattern(regexp = Consts.REGEX_PASSWORD) String newPassword)
            throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = getTokenObj();
        userInfoService.updatePassword(tokenObj.getUserId(), oldPassword, newPassword);
        return Result.success();
    }

    @PostMapping("/logout")
    public Result logout() throws NoAuthException {
        UserInfoToken tokenObj = getTokenObj();
        channelContextUtils.closeContext(tokenObj.getUserId());
        return Result.success();
    }
}
